package socket;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer02 {

    public static void main(String[] args) {
        try {
            ServerSocket serverSocket = new ServerSocket(8801);
            while (true) {
                Socket accept = serverSocket.accept();
                new Thread(() -> {
                    service(accept);
                }).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void service(Socket socket){
       try {
           System.out.println("收到请求---------");
           PrintWriter printWriter = new PrintWriter(socket.getOutputStream(),true);
           printWriter.println("HTTP/1.0 200 OK");
           printWriter.println("Content-Type:text/html;charset=UTF-8");
           String body = "<h1>Hello,nio1</h1>";
           printWriter.println("Content-Length:"+body.getBytes().length);
           printWriter.println(); //这个不能删除，区分响应报头与响应正文
           printWriter.write(body);
           printWriter.close();
           socket.close(); //这个关闭后才返回结果
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}
